
#include <QtWidgets>
#include <QtNetwork>
#include <QtWebKitWidgets>
#include <QtPrintSupport/QPrinter>
#include <QtPrintSupport/QPrintDialog>
#include <QtPrintSupport/QPrintPreviewDialog>
#include <QtPrintSupport/QPrinterInfo>
#include "mainwindow.h"


void printDocument(const QString &strHtml, const QString &strPdfFile, int iFormat = 1){
    QPrinter p;
    QTextDocument doc;
    doc.setHtml(strHtml);

    if (iFormat == 1){
        p.setPageSize(QPrinter::A4);
        p.setOutputFormat(QPrinter::PdfFormat);
        p.setOutputFileName(strPdfFile);
        doc.print(&p);
    }else{
        doc.setPageSize(QSizeF(p.logicalDpiX()*(80/25.4),p.logicalDpiY()*(297/25.4)));
        p.setOutputFormat(QPrinter::NativeFormat);
        doc.print(&p);
    }
}

void listPrinter(){
    QList<QPrinterInfo> list = QPrinterInfo::availablePrinters();
    for (int i = 0 ;i<list.size();i++){
        QPrinterInfo pi = list.at(i);
        qDebug() << pi.printerName();
        QPrinter printer(pi);
    }
}

void printWidget(QObject *widget){
    QPrinter printer;
    QPainter painter(&printer);
    painter.drawPixmap(0, 0, QPixmap::grabWidget(widget));
    painter.end();
}

//////////////////////////////

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    this->createWebView();
    this->showMenuBar(true);
    this->showAddressBar(true);
    this->showStatusBar(true);

    setUnifiedTitleAndToolBarOnMac(true);

    QDir dir;
    this->config = new QSettings(dir.currentPath()+"/config.ini", QSettings::IniFormat);
    this->config->setIniCodec("UTF-8");
    QString home_url = this->config->value("/config/home_url").toString();
    //QMessageBox::about(NULL, "PATH", home_url);

    this->loadUrl(home_url);

    //this->loadUrl(QUrl("http://www.qq.com"));

}

void MainWindow::createWebView(){
    this->webview = new QWebView(this);
    webview->settings()->setAttribute(QWebSettings::JavascriptEnabled, true);
    webview->settings()->setAttribute(QWebSettings::PluginsEnabled, false);
    webview->page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);

    //让QtWebKit使用缓存,返回的是系统的缓存目录的路径
    QNetworkDiskCache *diskCache=new QNetworkDiskCache(this);
    QString location=QStandardPaths::writableLocation(QStandardPaths::CacheLocation);
    diskCache->setCacheDirectory(location);
    webview->page()->networkAccessManager()->setCache(diskCache);

    this->setCentralWidget(this->webview);

    //connect(this->webview, SIGNAL(loadStarted()), SLOT(xx()));
    connect(this->webview, SIGNAL(titleChanged(QString)), SLOT(adjustTitle()));
    connect(this->webview, SIGNAL(linkClicked(QUrl)), SLOT(loadUrl(QUrl)));
}

void MainWindow::test(){
    printDocument("<!DOCTYPE html><html><body><div style=\"position: absolute;	left: 0px;	top: 0px;	width: 100px;	height: 80px;	z-index: 1;background-color: #006600;\">aaa</div></body></html>","d:\\print.pdf");
}

void MainWindow::loadUrl(const QUrl& url){
    webview->load(url);
}

void MainWindow::openFile(){
    QString filename;
    filename = QFileDialog::getOpenFileName(this, tr("选择图像"), "/", tr("所有文件 (*.*)"));
    if(filename.isEmpty()){
        return;
    }
    QUrl url = QUrl::fromUserInput(filename);
    this->loadUrl(url);
}

void MainWindow::showMenuBar(bool show){
    bool inited = menuBar()->children().size()==4;
    if(show && !inited){
        QMenu *fileMenu = menuBar()->addMenu(tr("&File"));
            QAction* openFileAction = new QAction("&Open File", this);
            QAction* printAction = new QAction("&Print ...", this);
            QAction* quitAction = new QAction("&Quit", this);
            fileMenu->addAction(openFileAction);
            fileMenu->addAction(printAction);
            fileMenu->addAction(quitAction);
            this->connect(printAction, SIGNAL(triggered()), SLOT(print()));
            this->connect(openFileAction, SIGNAL(triggered()), SLOT(openFile()));

        QMenu *viewMenu = menuBar()->addMenu(tr("&View"));
            QAction* viewSourceAction = new QAction("View &Source", this);
            viewMenu->addAction(viewSourceAction);
            this->connect(viewSourceAction, SIGNAL(triggered()), SLOT(viewSource()));

        QMenu *helpMenu = menuBar()->addMenu(tr("&Help"));
            QAction* testAction = new QAction("&test", this);
            helpMenu->addAction(testAction);
            this->connect(testAction, SIGNAL(triggered()), SLOT(test()));
    }
    if(inited){
        menuBar()->setVisible(show);
    }
}

void MainWindow::showAddressBar(bool show){
    bool inited = this->locationEdit!=0;
    if(show && !inited){
        this->locationEdit = new QLineEdit(this);
        this->locationEdit->setSizePolicy(QSizePolicy::Expanding, locationEdit->sizePolicy().verticalPolicy());
        this->connect(locationEdit, SIGNAL(returnPressed()), SLOT(changeLocation()));

        QToolBar *toolBar = addToolBar(tr("Navigation"));
        toolBar->addAction(webview->pageAction(QWebPage::Back));
        toolBar->addAction(webview->pageAction(QWebPage::Forward));
        toolBar->addAction(webview->pageAction(QWebPage::Reload));
        toolBar->addAction(webview->pageAction(QWebPage::Stop));
        toolBar->addWidget(locationEdit);

        connect(this->webview, SIGNAL(urlChanged(QUrl)), SLOT(adjustLocation()));
    }
    if(inited){
        QList<QToolBar *> toolbars = this->findChildren<QToolBar *>();
        for(int i=0;i<toolbars.length();i++){
            toolbars.at(i)->setVisible(show);
        }
    }

}

void MainWindow::showStatusBar(bool show){
    this->statusLabel = new QLabel();
    this->statusBar()->addWidget(this->statusLabel);
    connect(this->webview, SIGNAL(loadProgress(int)), SLOT(setProgress(int)));
}

void MainWindow::print(){
    QPrinter printer(QPrinter::HighResolution);

    QPrintPreviewDialog preview(&printer, this);
    connect(&preview, SIGNAL(paintRequested(QPrinter*)), SLOT(printPreview(QPrinter*)));
    preview.exec();

/*
    QPrintDialog printDlg(&printer, this);
    if(printDlg.exec())  {
        this->webview->page()->mainFrame()->print(&printer);
    }
*/
}

void MainWindow::printPreview (QPrinter *printer){
    this->webview->page()->mainFrame()->print(printer);
}

void MainWindow::changeLocation(){
    QUrl url = QUrl::fromUserInput(locationEdit->text());
    this->loadUrl(url);
    this->webview->setFocus();
}

void MainWindow::adjustLocation(){
    //locationEdit->setText(url.toString());
    locationEdit->setText(this->webview->url().toString());
}

void MainWindow::adjustTitle(){
    //this->setWindowTitle(title);
    this->setWindowTitle(this->webview->title());
}

void MainWindow::setProgress(int p){
    this->statusLabel->setText(QString("%1%").arg(p));
}

void MainWindow::viewSource(){
    QNetworkAccessManager* accessManager = webview->page()->networkAccessManager();
    QNetworkRequest request(webview->url());
    QNetworkReply* reply = accessManager->get(request);
    connect(reply, SIGNAL(finished()), this, SLOT(slotSourceDownloaded()));
}

void MainWindow::slotSourceDownloaded(){
    QNetworkReply* reply = qobject_cast<QNetworkReply*>(const_cast<QObject*>(sender()));
    QTextEdit* textEdit = new QTextEdit(NULL);
    textEdit->setAttribute(Qt::WA_DeleteOnClose);
    textEdit->show();
    textEdit->setPlainText(reply->readAll());
    reply->deleteLater();
}

MainWindow::~MainWindow(){

}

